#include <lgpl-components/cobjectmanager.h>

#include "cmessaginglayer.h"
#include "cprofilefactory.h"
#include "xmppprofile.h"

CMessagingLayer * CMessagingLayer::m_instance = 0;

CMessagingLayer::CMessagingLayer(QObject *parent) :
    QObject(parent),
    m_currentProfile(0)
{
    if (m_instance)
        qWarning("CMessaging layer already have instance");
    m_instance = this;

    registerProtocols();
}

CMessagingLayer::~CMessagingLayer()
{
    m_instance = 0;
}

CMessagingLayer * CMessagingLayer::instance()
{
    return m_instance;
}

CProfile * CMessagingLayer::currentProfile() const
{
    return m_currentProfile;
}

void CMessagingLayer::setProfile(const CAuthInfo &authInfo)
{
    if (!m_currentProfile) {
        m_currentProfile = CProfileFactory::getProfile(authInfo);
        connect(m_currentProfile, SIGNAL(messageReceived(CMessage)),
                this, SIGNAL(messageReceived(CMessage)));
    }
    else {
        if (m_currentProfile->authInfo() != authInfo) {
            m_currentProfile->deleteLater();
            m_currentProfile = CProfileFactory::getProfile(authInfo);
            connect(m_currentProfile, SIGNAL(messageReceived(CMessage)),
                    this, SIGNAL(messageReceived(CMessage)));
        }
    }
}

void CMessagingLayer::sendMessage(const QString &message, const ContactInfo &to)
{
    m_currentProfile->sendMessage(message, to);
}

ContactInfo CMessagingLayer::resolveUid(const QString &uid, const QString &networkId)
{
    if (m_currentProfile->networkId() == networkId) {
        return m_currentProfile->resolveUid(uid);
    } else
        return ContactInfo();
}

void CMessagingLayer::connectProfile()
{
    m_currentProfile->connectToNetwork();
}

void CMessagingLayer::disconnectProfile()
{
    m_currentProfile->disconnectFromNetwork();
}

void CMessagingLayer::registerProtocols()
{
    CObjectManager * manager = CObjectManager::instance();
    Q_ASSERT(manager);

    manager->add(new IXmppProfile(this));
    manager->add(new IVkontakteProfile(this));
}
